//
//  ImageADScrollView.m
//  testScrollViewViewController
//
//  Created by 陈区 on 13-12-11.
//  Copyright (c) 2013年 陈区 . All rights reserved.
//

#define kCurrentWidth LYScreenWidth()
#define kCurrrntHeight (LYScreenWidth() *0.5)

#import "ImageADScrollView.h"
#import "SEGBasicBussinessCommonDefine.h"
@interface ImageADScrollView()

- (void)loadImagesView;

- (void)initData;

- (void)turnPage;

- (void)runTimePage;

@end

@implementation ImageADScrollView

@synthesize delegate;

- (void)loadImagesView
{
    float width = kCurrentWidth;
    float height = kCurrrntHeight;
    UIView *imgView = nil;
    for (int i = 0 ; i < m_imageCount; i++)
    {
        if ([delegate respondsToSelector:@selector(imageADScrollView:atIndex:)])
        {
            imgView = [delegate imageADScrollView:self atIndex:i];
            imgView.contentMode = UIViewContentModeScaleAspectFill;
            [imgView.layer setMasksToBounds:YES];
            if (imgView)
            {
                imgView.frame = CGRectMake((width * i) + width, 0, width, height);
                [m_scrollView addSubview:imgView];
            }
        }
    }
    
    if ([delegate respondsToSelector:@selector(imageADScrollView:atIndex:)])
    {
        //取数组最后一张图片 放在第0页
        imgView = [delegate imageADScrollView:self atIndex:m_imageCount-1];
        imgView.frame = CGRectMake(0, 0, width, height); // 添加最后1页在首页 循环
        [m_scrollView addSubview:imgView];
        
        // 取数组第一张图片 放在最后1页 添加第1页在最后 循环
        imgView = [delegate imageADScrollView:self atIndex:0];
        imgView.frame = CGRectMake((width * (m_imageCount + 1)) , 0, width, height);
        [m_scrollView addSubview:imgView];
        
        //  +上第1页和第4页  原理：4-[1-2-3-4]-1
        [m_scrollView setContentSize:CGSizeMake(width * (m_imageCount + 2), height)];
        [m_scrollView setContentOffset:CGPointMake(0, 0)];
        // 默认从序号1位置放第1页 ，序号0位置位置放第4页
        [m_scrollView scrollRectToVisible:CGRectMake(width,0,width,height) animated:NO];
    }
}

- (void)initData
{
    if ([delegate respondsToSelector:@selector(numberOfImagesInImageADScrollView:)])
    {
        m_imageCount = [delegate numberOfImagesInImageADScrollView:self];
        
        m_pageControl.numberOfPages = m_imageCount;
        CGSize pointSize = [m_pageControl sizeForNumberOfPages:m_imageCount];
        m_pageControl.frame = CGRectMake(kCurrentWidth - pointSize.width - 10, kCurrrntHeight - 20, pointSize.width, 10);
    }
}

- (void)reloadData
{
    [self initData];
    
    NSArray *subViewArray = [m_scrollView subviews];
    for (long i = [subViewArray count] - 1; i >= 0; i--)
    {
        UIView *subView = [subViewArray objectAtIndex:i];
        [subView removeFromSuperview];
    }
    
    [self loadImagesView];
    
    NSInteger totalNumber = 0;
    if ([self.delegate respondsToSelector:@selector(numberOfImagesInImageADScrollView:)]) {
        totalNumber = [self.delegate numberOfImagesInImageADScrollView:self];
    }
    m_scrollView.scrollEnabled = totalNumber > 1 ? YES : NO;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        m_scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        m_scrollView.bounces = YES;
        m_scrollView.pagingEnabled = YES;
        m_scrollView.delegate = self;
        m_scrollView.userInteractionEnabled = YES;
        m_scrollView.showsHorizontalScrollIndicator = NO;
        [self addSubview:m_scrollView];
        
        m_timer = [NSTimer scheduledTimerWithTimeInterval:AD_PAGE_COUNT
                                                    target:self
                                                  selector:@selector(runTimePage)
                                                  userInfo:nil
                                                   repeats:YES];

        m_pageControl = [[UIPageControl alloc]init];
        CGSize pointSize = [m_pageControl sizeForNumberOfPages:m_imageCount];
        m_pageControl.frame = CGRectMake(frame.size.width - pointSize.width - 10, frame.size.height - 20, pointSize.width, 10);
        m_pageControl.numberOfPages = m_imageCount;
        m_pageControl.currentPage = 0;
        m_pageControl.hidesForSinglePage=YES;
        [m_pageControl addTarget:self action:@selector(turnPage) forControlEvents:UIControlEventValueChanged];
        [self addSubview:m_pageControl];
    }
    return self;
}


- (void)dealloc
{
    if ([m_timer isValid])
    {
        [m_timer invalidate];
    }
}


- (void)turnPage
{
    float width = kCurrentWidth;
    float height = kCurrrntHeight;
    
    
    long page = m_pageControl.currentPage; // 获取当前的page
    // 触摸pagecontroller那个点点 往后翻一页 +1
    [m_scrollView scrollRectToVisible:CGRectMake(width*(page+1),0,width,height) animated:NO];
}

- (void)runTimePage
{
    long page = m_pageControl.currentPage; // 获取当前的page

    page++;
    page = page > m_imageCount-1 ? 0 : page ;
    m_pageControl.currentPage = page;
    [self turnPage];
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)sender
{
    CGFloat pagewidth = m_scrollView.frame.size.width;
    int page = floor((m_scrollView.contentOffset.x - pagewidth/(m_imageCount+2))/pagewidth)+1;
    page --;  // 默认从第二页开始
    m_pageControl.currentPage = page;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    float width = kCurrentWidth;
    float height = kCurrrntHeight;
    CGFloat pagewidth = m_scrollView.frame.size.width;
    int currentPage = floor((m_scrollView.contentOffset.x - pagewidth/ (m_imageCount+2)) / pagewidth) + 1;
    if (currentPage==0)
    {
        [m_scrollView scrollRectToVisible:CGRectMake(width * m_imageCount,0,width,height) animated:NO]; // 序号0 最后1页
    }
    else if (currentPage==(m_imageCount+1))
    {
        [m_scrollView scrollRectToVisible:CGRectMake(width,0,width,height) animated:NO]; // 最后+1,循环第1页
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (m_timer &&  [m_timer isValid])
    {
        [m_timer invalidate];
        m_timer = nil;
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (m_timer &&  [m_timer isValid])
    {
        [m_timer invalidate];
        m_timer = nil;
    }
    
    m_timer = [NSTimer scheduledTimerWithTimeInterval:AD_PAGE_COUNT
                                                target:self
                                              selector:@selector(runTimePage)
                                              userInfo:nil
                                               repeats:YES];
}

@end
